package service

import (
	"errors"

	"gorm.io/gorm"

	"admin-nexus-backend/internal/dto"
	"admin-nexus-backend/internal/model"
)

// CityService 城市管理服务
type CityService struct {
	db *gorm.DB
}

// NewCityService 创建城市服务实例
func NewCityService(db *gorm.DB) *CityService {
	return &CityService{db: db}
}

// GetCityList 获取城市列表
func (s *CityService) GetCityList(req *dto.CityListRequest) (*dto.PageResult, error) {
	var cities []model.City
	var total int64

	query := s.db.Model(&model.City{})

	// 条件筛选
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.ProvinceName != "" {
		query = query.Where("province_name LIKE ?", "%"+req.ProvinceName+"%")
	}
	if req.Status != nil {
		query = query.Where("status = ?", *req.Status)
	}

	// 计算总数
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 排序
	sortBy := "sort"
	if req.SortBy != "" {
		sortBy = req.SortBy
	}
	order := "ASC"
	if req.Order == "desc" {
		order = "DESC"
	}
	query = query.Order(sortBy + " " + order)

	// 分页
	offset := (req.Page - 1) * req.PageSize
	if err := query.Offset(offset).Limit(req.PageSize).Find(&cities).Error; err != nil {
		return nil, err
	}

	// 转换为响应DTO
	var items []dto.CityResponse
	for _, city := range cities {
		items = append(items, dto.CityResponse{
			ID:           city.ID,
			Name:         city.Name,
			Code:         city.Code,
			ProvinceID:   city.ProvinceID,
			ProvinceName: city.ProvinceName,
			Status:       city.Status,
			Sort:         city.Sort,
			CreatedAt:    city.CreatedAt,
			UpdatedAt:    city.UpdatedAt,
		})
	}

	return &dto.PageResult{
		List:     items,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, nil
}

// GetCityByID 根据ID获取城市信息
func (s *CityService) GetCityByID(id uint) (*dto.CityResponse, error) {
	var city model.City
	if err := s.db.First(&city, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("城市不存在")
		}
		return nil, err
	}

	return &dto.CityResponse{
		ID:           city.ID,
		Name:         city.Name,
		Code:         city.Code,
		ProvinceID:   city.ProvinceID,
		ProvinceName: city.ProvinceName,
		Status:       city.Status,
		Sort:         city.Sort,
		CreatedAt:    city.CreatedAt,
		UpdatedAt:    city.UpdatedAt,
	}, nil
}

// CreateCity 创建城市
func (s *CityService) CreateCity(req *dto.CityCreateRequest) error {
	// 检查城市名称是否已存在
	var count int64
	if err := s.db.Model(&model.City{}).Where("name = ?", req.Name).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("城市名称已存在")
	}

	city := model.City{
		Name:         req.Name,
		Code:         req.Code,
		ProvinceID:   req.ProvinceID,
		ProvinceName: req.ProvinceName,
		Status:       req.Status,
		Sort:         req.Sort,
	}

	return s.db.Create(&city).Error
}

// UpdateCity 更新城市
func (s *CityService) UpdateCity(id uint, req *dto.CityUpdateRequest) error {
	// 检查城市是否存在
	var city model.City
	if err := s.db.First(&city, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("城市不存在")
		}
		return err
	}

	// 检查城市名称是否重复（如果修改了名称）
	if req.Name != "" && req.Name != city.Name {
		var count int64
		if err := s.db.Model(&model.City{}).Where("name = ? AND id != ?", req.Name, id).Count(&count).Error; err != nil {
			return err
		}
		if count > 0 {
			return errors.New("城市名称已存在")
		}
	}

	// 更新字段
	updateData := make(map[string]interface{})
	if req.Name != "" {
		updateData["name"] = req.Name
	}
	updateData["code"] = req.Code
	updateData["province_id"] = req.ProvinceID
	updateData["province_name"] = req.ProvinceName
	updateData["status"] = req.Status
	updateData["sort"] = req.Sort

	return s.db.Model(&city).Updates(updateData).Error
}

// DeleteCity 删除城市
func (s *CityService) DeleteCity(id uint) error {
	// 检查城市是否存在
	var city model.City
	if err := s.db.First(&city, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("城市不存在")
		}
		return err
	}

	return s.db.Delete(&city).Error
}

// BatchDeleteCity 批量删除城市
func (s *CityService) BatchDeleteCity(req *dto.CityBatchDeleteRequest) error {
	// 检查是否所有ID都存在
	var count int64
	if err := s.db.Model(&model.City{}).Where("id IN ?", req.IDs).Count(&count).Error; err != nil {
		return err
	}
	if int(count) != len(req.IDs) {
		return errors.New("部分城市不存在")
	}

	return s.db.Where("id IN ?", req.IDs).Delete(&model.City{}).Error
}
